<template>
  <!--测试 原生 防抖 -->
  el-input：<el-input v-model="val" placeholder="测试 原生 防抖"></el-input>
  <br>
  input：<input v-model="val" />
  <br>
  ({{val}})
</template>

<script lang="ts">
  import { defineComponent, customRef } from 'vue'
  import { ElInput } from 'element-plus'

  function useDebouncedRef(value: any, delay = 500) {
    let timeout: NodeJS.Timeout
    return customRef((track, trigger) => {
      return {
        get() {
          track()
          return value
        },
        set(newValue) {
          clearTimeout(timeout)
          timeout = setTimeout(() => {
            value = newValue
            trigger()
          }, delay)
        }
      }
    })
  }

  /**
   * 原生防抖
   */
  export default defineComponent({
    name: 'nf-deb-cus-ref',
    components: {
      ElInput,
    },
    props: {
      modelValue: {
        type: [String, Number, Boolean, Date]
      }
    },
    setup(props, context) {

      const val = useDebouncedRef('')

      return {
        val
      }
    }
  })
</script>